
package com.dyzx.hbb.security.model;

import com.dyzx.hbb.modules.sys.entity.SysUser;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    /**
     * 获取用户ID
     */
    public Long getId() {
        return user != null ? user.getId() : null;
    }

    /**
     * 是否为管理员
     */
    public boolean isAdmin() {
        return user != null && user.getOrganId() != null && user.getOrganId() == 1;
    }


    private SysUser user;


    /**
     * -- GETTER --
     *  获取部门ID
     */
    @Getter
    private Long deptId;
    private Long organId;

    /**
     * -- GETTER --
     *  获取数据权限范围
     */
    @Getter
    private String dataScope;
    
    private List<String> permissions;
    
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(SysUser user, List<String> permissions, String dataScope) {
        this.user = user;
        System.out.println("user: " + user.getAccount());
        this.deptId = user.getDeptId();
        this.organId = user.getOrganId();
        this.dataScope = dataScope;
        this.permissions = permissions;
        
        // 转换权限
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        
        // 添加基本权限
        if (permissions != null) {
            for (String permission : permissions) {
                if (permission != null && !permission.trim().isEmpty()) {
                    System.out.println("Adding permission: " + permission);
                    authorityList.add(new SimpleGrantedAuthority(permission));
                }
            }
        }

        
        this.authorities = authorityList;
        System.out.println("Final authorities for user " + user.getAccount() + ": " + authorityList);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1;
    }


}